package com.source.jucutils;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author wengqy
 * @Date 2021/1/20
 */
public class SemaphoreDDemo {

    public static  int users = 100;
    public  static  int downTotal = 5000;

    public static AtomicInteger  atomicInteger  =  new AtomicInteger();

    public static void main(String[] args) {
        ExecutorService executors = Executors.newCachedThreadPool();
        Semaphore semaphore  = new Semaphore(users);

        System.out.println("main task  execuying  ............");
        for (int i =1; i <= downTotal; i++) {
            executors.execute(()->{

                try {
                    semaphore.acquire();
                    add();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore.release();
                }
            });
        }

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executors.shutdown();

        System.out.println("最后的职位："+ atomicInteger.get());
    }


    public static void  add(){
        System.out.println("当前的线程为： ------》"+Thread.currentThread().getName());
        atomicInteger.getAndIncrement();
    }
}
